import React,{ useState }from 'react'
import {Upload} from 'antd'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
export default function Main() {
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState("");
  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
    </div>
  );

  const getBase64 = (img, callback) => {
    //文件流
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
  };
  //使用它来进行上传之后得到响应
  const handleChange=(info)=>{
    if(info.file.status === 'uploading') {
      setLoading(true);
      return;
    }
    if (info.file.status === 'done') {
      //setLoading(false)
      // console.log(info.file.response.data[0]);
      // setImageUrl(info.file.response.data[0])

      getBase64(info.file.originFileObj, (url) => {
        setLoading(false);
        console.log(url);
        setImageUrl(url);
      });
    }
  }
  return (
    <div>
      <Upload
        name="file"
        action="http://47.98.128.191:3000/images/uploadImages"
        listType="picture-card"
        className="avatar-uploader"
        showUploadList={false}
        onChange={handleChange}
        headers={{Authorization:localStorage.getItem('token')}}>
        {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
      </Upload>
    </div>
  )
}
